package com.lifesting.tool.encoding;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

public class Activator extends AbstractUIPlugin {
	public static final String PLUGIN_ID = "com.lifesting.tool.encoding";
	public static final String ALL_ENCODING = "all";
	public static final List<String> ENCODINGS = Arrays.asList(new String[] { "GBK", "GB18030", "GB2312", "UTF-8",
			"ISO-8859-1", "US-ASCII", "UTF-16", "UTF-16BE", "UTF-16LE" });
	public static final List<String> FROM_ENCODINGS = Arrays.asList(new String[] { "all", "GBK", "GB18030", "GB2312",
			"UTF-8", "ISO-8859-1", "US-ASCII", "UTF-16", "UTF-16BE", "UTF-16LE" });
	private static int suffix_counter = 0;
	public static final String FILE = "setting.dat123456";
	public static final String DUMP = "DUMP";
	private static Activator plugin;

	public static void logException(Exception e) {
		IStatus status = new Status(4, "com.lifesting.tool.encoding", e.getLocalizedMessage(), e);
		getDefault().getLog().log(status);
	}

	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	public static Activator getDefault() {
		return plugin;
	}

	public static Setting newDefaultSetting() {
		suffix_counter += 1;
		return new Setting("s" + suffix_counter, "ISO-8859-1", "GBK", true);
	}

	public static synchronized void loadSetting(String projectName, List<Setting> settings) {
		File file = getDefault().getStateLocation().append(projectName + "_" + "setting.dat123456").toFile();
		if (file.exists()) {
			ObjectInputStream input = null;
			try {
				input = new ObjectInputStream(new FileInputStream(file));
				Object o;
				while (!(o = input.readObject()).equals(Activator.DUMP)) {
					// Object o;
					settings.add((Setting) o);
				}
			} catch (FileNotFoundException e) {
				logException(e);
				if (input != null) {
					try {
						input.close();
					} catch (IOException e1) {
						logException(e1);
					}
				}
			} catch (IOException e) {
				logException(e);
				if (input != null) {
					try {
						input.close();
					} catch (IOException e1) {
						logException(e1);
					}
				}
			} catch (ClassNotFoundException e) {
				logException(e);
				if (input != null) {
					try {
						input.close();
					} catch (IOException e1) {
						logException(e1);
					}
				}
			} finally {
				if (input != null) {
					try {
						input.close();
					} catch (IOException e) {
						logException(e);
					}
				}
			}
		}
	}
}
